package org.jeecg.modules.power.shop.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.exception.ChechDataAuthException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.app.util.NumberArithmeticUtils;
import org.jeecg.modules.app.v1.shop.entity.ApiAddShopEntity;
import org.jeecg.modules.app.v1.shop.entity.ApiListShopEntity;
import org.jeecg.modules.app.v1.shop.entity.ApiShopEntity;
import org.jeecg.modules.app.v1.util.Const;
import org.jeecg.modules.power.config.service.IYlCheckConfigService;
import org.jeecg.modules.power.device.entity.YlDevice;
import org.jeecg.modules.power.device.service.IYlDeviceRecordsService;
import org.jeecg.modules.power.device.service.IYlDeviceService;
import org.jeecg.modules.power.group.entity.GroupUser;
import org.jeecg.modules.power.shop.entity.YlShop;
import org.jeecg.modules.power.shop.entity.YlShopCategory;
import org.jeecg.modules.power.shop.mapper.YlShopMapper;
import org.jeecg.modules.power.shop.service.IYlShopCategoryService;
import org.jeecg.modules.power.shop.service.IYlShopService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * @Description: 门店表
 * @Author: jeecg-boot
 * @Date:   2024-07-08
 * @Version: V1.0
 */
@Service
@RequiredArgsConstructor
public class YlShopServiceImpl extends ServiceImpl<YlShopMapper, YlShop> implements IYlShopService {

    private final IYlShopCategoryService shopCategoryService;
    private final IYlDeviceRecordsService deviceRecordsService;
    private final IYlCheckConfigService configService;
    private final ISysUserService sysUserService;


    /**--------------------------------------------接口使用-------------------------------------------------------------------------*/
    @Override
    public void saveShopInfo(ApiAddShopEntity entity,SysUser bd) {
        YlShop shop = new YlShop();
        BeanUtils.copyProperties(entity,shop);
        Date date = new Date();
        shop.setCreateTime(date);
        shop.setCreateBy(entity.getShopBd());
        shop.setUpdateTime(date);
        shop.setUpdateBy(entity.getShopBd());
        String shopId = NumberArithmeticUtils.getTimestamp();
        shop.setId(shopId);
        /**
         * check 1 需要审核2直接通过不审核
         */
        Integer check = configService.getCheckShop()==1?2:1; //1自动审核2手动审核
        shop.setShopStatus(check);

        /***
         * 处理设备
         * 1、如果直接自动审核直接绑定当前设备。
         *   如果需要审核，则先把设备信息存储起来，然后等待审核通过后在进行绑定操作。
         */
        if(check==2) {
            deviceRecordsService.bind(entity.getDevice(), shop, bd, "自动审核通过");
        }else {
            /**
             * 对设备加锁保护，防止审核期间，设备进行别的操作，影响后续审核。审核通过后解锁。
             */
            String businessId = String.format(Const.device_business_id_A,shopId);
            deviceRecordsService.lockDevice(entity.getDevice(),businessId);
            shop.setShopRemark(JSON.toJSONString(entity.getDevice()));
        }
        this.save(shop);
    }

    @Override
    public void editShopInfo(ApiAddShopEntity entity) {
        YlShop shop = this.getById(entity.getId());
        if(shop == null )return;
        BeanUtils.copyProperties(entity,shop);
        shop.setUpdateTime(new Date());
        shop.setUpdateBy(entity.getShopBd());
        this.updateById(shop);
    }

    /**
     * 门店列表
     * @param lat
     * @param lng
     * @param shopName
     * @return
     */
    public List<ApiListShopEntity> list(String lat, String lng, String shopName, Integer distance,Integer number){
        return baseMapper.shopList( lat, lng, shopName,distance,number);
    }

    @Override
    public IPage<ApiListShopEntity> mylist(Page<ApiListShopEntity> page, String lat, String lng, String shopName, String shopBd,String shopStatus) {
        return baseMapper.myShopList(page, lat, lng, shopName, shopBd,shopStatus);
    }
    @Override
    public IPage<ApiListShopEntity> otherShopList(Page<ApiListShopEntity> page, String lat, String lng, String status,String shopName,  String shopBd) {
        return baseMapper.otherShopList(page, lat, lng, status,shopName, shopBd);
    }
    @Override
    public IPage<ApiListShopEntity> collectList(Page<ApiListShopEntity> page, String lat, String lng,String shopName,  String shopBd) {
        return baseMapper.collectList(page, lat, lng, shopName,shopBd);
    }

    /**
     * 门店详情
     * @param id
     * @return
     */
    @Override
    public ApiShopEntity myShopDetail(String id) {
        ApiShopEntity shop = baseMapper.myShopDetail(id);
        StringJoiner stringJoiner = new StringJoiner("/");
        YlShopCategory shopCategory = shopCategoryService.getById(shop.getShopCategory());
        stringJoiner.add(shopCategory.getCategoryName());
        boolean res = Objects.equals(shopCategory.getParentId(),"0")?false:true;
        while(res){
            shopCategory = shopCategoryService.getById(shopCategory.getParentId());
            stringJoiner.add(shopCategory.getCategoryName());
            if(Objects.equals(shopCategory.getParentId(),"0"))res = false;
        }
        shop.setShopCategory(stringJoiner.toString());
        return shop;
    }

    /**
     * 解绑到公海
     * @param shopId
     * @param user
     */
    @Transactional
    public void sea(String shopId, SysUser user){
        YlShop shop = this.getById(shopId);
        if(oConvertUtils.isEmpty(shop))throw  new ChechDataAuthException("解绑失败，未获取到门店信息。");
        if(!Objects.equals(shop.getBdId(),user.getId()))throw  new ChechDataAuthException("解绑失败，不能操作其他BD下的门店。");

        /**
         * 判定门店下是否还有设备未解绑
         */
        int count = deviceRecordsService.countShopDevice(shopId);
        if(count>0)throw new ChechDataAuthException("解绑失败，请先解绑门店下设备。");

        UpdateWrapper wrapper = new UpdateWrapper();;
        wrapper.set("shop_status", Const.shop_status_4);
        wrapper.set("shop_bd", "");
        wrapper.set("bd_id", "");
        wrapper.set("org_id", "");
        wrapper.eq("id",shopId);
        this.update(wrapper);
    }

    /**
     * 从公海认领门店
     * @param shopId
     * @param user
     */
    @Transactional
    public void claim(String shopId, SysUser user){
        YlShop shop = this.getById(shopId);
        if(oConvertUtils.isEmpty(shop))throw  new ChechDataAuthException("认领失败，未获取到门店信息。");
        if(oConvertUtils.isNotEmpty(shop.getBdId()))throw  new ChechDataAuthException("认领失败，晚来一步，门店已被其他BD认领。");

        GroupUser groupUser = deviceRecordsService.getGroupUser(user.getId());
        Date date = new Date();
        UpdateWrapper wrapper = new UpdateWrapper();;
        wrapper.set("shop_status", Const.shop_status_2);
        wrapper.set("shop_bd",groupUser.getUserName());
        wrapper.set("bd_id", groupUser.getUserId());
        wrapper.set("org_id", groupUser.getGroupId());
        wrapper.set("claim_time", date);
        wrapper.eq("id",shopId);
        this.update(wrapper);

        /**
         * 认领后，暂时记录无设备门店记录，超7天未绑定设备直接进入公海
         */
        LocalDateTime dateTime = LocalDateTime.now().plusDays(7);
        String unbindTime = dateTime.toString();
        String unbindDate = dateTime.toLocalDate().toString();
        deviceRecordsService.saveEmptyShopRecords(shopId,unbindTime,unbindDate);
    }

    /**--------------------------------------------接口使用-------------------------------------------------------------------------*/



    /**--------------------------------------------后台使用-------------------------------------------------------------------------*/

    /**
     * 后台门店审核
     * @param shop 审核门店信息
     * @return
     */
    public void check(YlShop shop){
        Gson gson = new GsonBuilder().create();
        shop.setClaimTime(new Date());
        Type listType = new TypeToken<List<ApiAddShopEntity.DeviceInfo>>() {}.getType();
        List<ApiAddShopEntity.DeviceInfo> lists = gson.fromJson(shop.getShopRemark(), listType);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        /**
         * 2通过3驳回
         */
        Integer status = shop.getShopStatus();
        if(status==2 && oConvertUtils.isNotEmpty(shop.getShopRemark())){
            SysUser bd = sysUserService.getById(shop.getBdId());
            deviceRecordsService.bind(lists, shop, bd,user.getRealname()+"后台审核通过");
        }
        shop.setShopRemark("");//去掉之前暂存的设备信息
        this.updateById(shop);
        String businessId = String.format(Const.device_business_id_A,shop.getId());
        deviceRecordsService.lockDevice(lists,businessId);
    }


    @Override
    public int getShopQuantity(String name) {
        return baseMapper.getShopQuantity(name);
    }





    /**--------------------------------------------后台使用-------------------------------------------------------------------------*/


    /**--------------------------------------------mi接口使用-------------------------------------------------------------------------*/
    /**mi
     * 获取上个月 新增的门店数据
     * @return
     */
    @Override
    public List<YlShop> getLastMonthShop() {
        return baseMapper.getLastMonthShop();
    }
    /**
     * 获取本月新增的门店数据
     * @param jDate 截止时间
     * @return
     */
    @Override
    public List<YlShop> getThisMonthShop(String jDate) {
        return baseMapper.getThisMonthShop(jDate);
    }



    /**
     * app首页统计 近多少天的数据
     * @param day 近几天
     * @param bdId  业务员id
     * @param groupId 小组id
     * @return
     */
    @Override
    public Integer getHomeShopStatistics(Integer day, String bdId, String groupId) {
        return baseMapper.getHomeShopStatistics(day, bdId, groupId);
    }
    /**
     * app首页统计 近多少天的数据 折线图
     * @param day 近几天
     * @param bdId  业务员id
     * @param groupId 小组id
     * @return
     */
    @Override
    public List<Map> getHomeShopLineChart(Integer day, String bdId, String groupId) {
        return baseMapper.getHomeShopLineChart(day, bdId, groupId);
    }
    /**mi
     *  APP运营端-新增门店-2级页面- 店铺数据
     * @param type 时间类型（1今日、2昨日、3本周、4本月）
     * @param bdId 业务员id
     * @param groupId 小组id
     * @return
     */
    @Override
    public List<Map> getAddShopList(Integer type, String bdId, String groupId) {
        return baseMapper.getAddShopList(type, bdId, groupId);
    }

    /**
     * 根据 群组 获取 业务员id  获取 门店数据  getShopByIdList
     * @param bdId 业务员id
     * @param groupId 小组id
     * @return
     */
    @Override
    public List<String> getShopByIdList(String bdId, String groupId) {
        return baseMapper.getShopByIdList(bdId, groupId);
    }


    /**--------------------------------------------mi接口使用-------------------------------------------------------------------------*/

}
